import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ConfirmationService } from 'primeng/api';
import { FieldType } from 'src/components/scenarios/enums';
import { FieldMapConfig, FieldValueMap } from 'src/components/scenarios/models';
import { v4 as guid } from "uuid";
import { StatusConfigDialogComponent } from './status-config-dialog/status-config-dialog.component';

@Component({
  selector: 'app-status-config',
  templateUrl: './status-config.component.html',
  styleUrl: './status-config.component.scss'
})
export class StatusConfigComponent {
  types: FieldType[] = Object.values(FieldType);

  _cfg: FieldMapConfig = {
    Id: "",
    Name: "Status",
    FontSize: 12,
    Type: FieldType.Int16,
    Maps: [],
    Visible: true
  };
  @ViewChild("configDialog", { static: true })
  configDialog!: StatusConfigDialogComponent;
  @Input()
  get config() {
    return this._cfg;
  }
  set config(cfg: FieldMapConfig) {
    if (!cfg) {
      this._cfg = {
        Id: "",
        Name: "Status",
        FontSize: 12,
        Type: FieldType.Int16,
        Maps: [],
        Visible: true,
      };
    } else {
      this._cfg = cfg;
      this._cfg.Name = cfg.Name ?? "Status";
      this._cfg.Type = cfg.Type ?? FieldType.Int16;
    }
    this.configChange.emit(this._cfg);
  }

  @Output()
  configChange: EventEmitter<FieldMapConfig> = new EventEmitter();

  constructor(private confirmService: ConfirmationService) {
  }

  onEditStatus(status: FieldValueMap) {
    this.configDialog.onShow(status);
  }
  onDeleteStatus(status: FieldValueMap) {
    this.confirmService.confirm({
      message: '确定删除该记录?',
      header: '删除确认',
      icon: 'pi pi-info-circle',
      acceptButtonStyleClass: "p-button-danger p-button-text",
      rejectButtonStyleClass: "p-button-text p-button-text",
      acceptIcon: "none",
      rejectIcon: "none",
      accept: () => {
        this.config.Maps = this.config.Maps.filter(item => item.Id != status.Id);
      },
      reject: () => {
      }
    });
  }
  onAddStatusClick() {
    this.configDialog.onShow();
  }

  onEditStatusConfirm(status: FieldValueMap) {
    if (status.Id) {
      this.config.Maps = this.config.Maps.map(item => item.Id === status.Id ? status : item);
    } else {
      this.config.Maps.push({ ...status, Id: guid() });
    }
  }
}
